﻿using System.Windows.Forms;
using System;
using System.IO;
using System.IO.Pipes;
using System.Drawing; // For Image class. Add System.Drawing.Common NuGet for .NET Core/5+
using System.Threading.Tasks;


namespace PipeIsNet
{
    public partial class Form1 : Form
    {

        // 命名管道的名称，必须与C++服务器一致

        const string ServerName = "."; // "." 表示本地机器
        static   string pipeNameToUse = "MyImagePipe"; // 与C++服务器端使用的管道名称一致
      NamedPipeImageReceiver NamedPipereceiver = new NamedPipeImageReceiver(pipeNameToUse);

        SharedMemoryImageReceiver Memoryreceiver = new SharedMemoryImageReceiver();

        public Form1()
        {
            InitializeComponent();

        }

    


        private void Form1_Load(object sender, System.EventArgs e)
        {
        

        }

        //共享内存通信读取图像
        private async  void ReadImage_SharedMemory()
        {

            if (Memoryreceiver.Initialize())
            {

                Image img = await Memoryreceiver.ReceiveImageAsync(timeoutMilliseconds: 15000); // 等待15秒

                if (img != null)
                {
                    Console.WriteLine("[主程序 C#] 成功接收到图像。");
                    try
                    {
                        string fileName = $"CSharp_MMF接收的图像_{DateTime.Now:yyyyMMdd_HHmmss}.png";
                        img.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
                        Console.WriteLine($"[主程序 C#] 图像已保存为: {fileName}");
                        img.Dispose();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"[主程序 C#] 保存图像时出错: {ex.Message}");
                        img?.Dispose();
                    }
                }
                else
                {
                    Console.WriteLine("[主程序 C#] 未能接收到图像或超时。");
                }


            }
            else
            {
                Console.WriteLine("[主程序 C#] 连接到共享内存服务失败。请确保C++发送端已启动并创建了共享资源。");
            }

        }

        // 管道通信读取图像
        private async void ReadImage()
        {



            // --- 模拟 "接收图像" 按钮点击 ---
            Console.WriteLine("[主程序] 用户点击“接收图像”按钮。");
            Image receivedImage = await NamedPipereceiver.ReceiveImageAsync();

            if (receivedImage != null)
            {
                Console.WriteLine("[主程序] 成功接收到图像对象。");
                try
                {
                    // 在GUI中，你会将 image 显示在 PictureBox 中
                    // pictureBox.Image = receivedImage;
                    // 这里我们将其保存到文件
                    string outputFileName = $"CSharp_接收的图像_{DateTime.Now:yyyyMMdd_HHmmss}.png";
                    receivedImage.Save(outputFileName, System.Drawing.Imaging.ImageFormat.Png);
                    Console.WriteLine($"[主程序] 图像已保存为: {outputFileName}");

                    // 重要: 如果图像对象不再由UI控件管理，应手动释放
                    receivedImage.Dispose();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[主程序] 保存或处理图像时发生错误：{ex.Message}");
                    receivedImage?.Dispose(); // 确保即使出错也尝试释放
                }
            }
            else
            {
                Console.WriteLine("[主程序] 未能接收到图像或接收过程中发生错误。");
            }




        }



        ////管道通信连接服务器
        private async void ConnectToServer()
        {

            Console.WriteLine("[主程序] 用户点击“连接服务器”按钮。");
            if (await NamedPipereceiver.ConnectAsync(timeoutMilliseconds: 10000)) // 增加超时以便有时间启动服务器
            {
                Console.WriteLine("[主程序] 连接成功！");
            }
            else
            {
                Console.WriteLine($"[主程序] 连接到管道 '{pipeNameToUse}' 失败。请确保C++服务器端正在运行并使用相同的管道名称。");


            }

        }

        ////管道通信断开连接
        private void DisconnectFromServer()
        {
            Console.WriteLine("[主程序] 清理并退出。");
            NamedPipereceiver.Dispose(); // 调用Dispose来清理

            Console.WriteLine("按任意键结束...");
            if (!Console.IsInputRedirected) // 仅在交互式控制台中等待按键
            {
                Console.ReadKey();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

               ConnectToServer();

 



        }

        private void button3_Click(object sender, EventArgs e)
        {
           DisconnectFromServer();

        }

        private void button2_Click(object sender, EventArgs e)
        {
            ReadImage();
        }

        private void button5_Click(object sender, EventArgs e)
        {
     
        }

        private void button4_Click(object sender, EventArgs e)
        {
            ReadImage_SharedMemory();
        }
    }
}
